package com.houdoudou.customer.buy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.houdoudou.bean.Car;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.bean.Product;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.AsynImageLoader;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.ListViewUtil;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.me.LoginAct;
import com.houdoudou.customer.me.RegistAct;
import com.houdoudou.customer.sqlite.CarDao;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;


import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class PlaceOrderAct extends FragmentActivity{

	
	ListView productListView;
	JSONObject orderJO;
	JSONArray  productsJA;
    ListAdapter productAdapter;
	AsynImageLoader imageLoader;
	TextView shopName, serviceTelnum;
	TextView customer,address,timeAA;
	TextView moneyProduct,moneyFreight,moneyCu;
	TextView productnum,productVolume;
	EditText note;
	ProgressBar prgs;
	Button confirm;
	Spinner sp_date;
	View.OnClickListener myClickListener;
	ImageButton back;
	 boolean islate;
	 boolean isDateSelected=false;
	List<Date> dates= new ArrayList<Date>();
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.act_place_order);
		orderJO= JSONObject.fromObject(getIntent().getStringExtra("orderJO"));
		System.out.println("act playce order oncreate  orderJO="+orderJO);
		productsJA= orderJO.getJSONArray("products");
		initListenr();
		imageLoader= new AsynImageLoader(this);
		
		productListView= (ListView) findViewById(R.id.listview_act_placeorder);
		back= (ImageButton) findViewById(R.id.back_act_placeorder);
		moneyCu= (TextView) findViewById(R.id.tv_moneycu_act_placeorder);
		confirm= (Button) findViewById(R.id.btn_confirm_act_placeorder);
		shopName= (TextView) findViewById(R.id.tv_shopname_act_placeorder);
		serviceTelnum=(TextView) findViewById(R.id.tv_servicetel_act_placeorder);
		customer=(TextView) findViewById(R.id.tv_customertel_act_placeorder);
		address=(TextView) findViewById(R.id.tv_machineaddress_act_placeorder);
		timeAA=(TextView) findViewById(R.id.tv_arrivetime_act_placeorder);
		moneyProduct=(TextView) findViewById(R.id.tv_moneyproduct_act_placeorder);
		moneyFreight=(TextView) findViewById(R.id.tv_moneyfreight_act_placeorder);
		productVolume=(TextView) findViewById(R.id.tv_productvolume_act_placeorder);
		productnum=(TextView) findViewById(R.id.tv_productnum_act_placeorder);
		prgs= (ProgressBar) findViewById(R.id.prgs_act_placeorder);
		note= (EditText) findViewById(R.id.et_note_act_placeorder);
		
		productAdapter= new ProductListAdapter(this);
		productListView.setAdapter(productAdapter);
		ListViewUtil.setListViewHeightBasedOnChildren(productListView);	
		sp_date= (Spinner) findViewById(R.id.sp_date_act_placeorder);	 
		initDateAdapter();
	    back.setOnClickListener(myClickListener);
		
		confirm.setOnClickListener(myClickListener);
	
		moneyCu.setText("￥"+orderJO.getDouble(Order.MONEYCU)); 
		moneyFreight.setText("￥"+orderJO.getDouble(Order.MONEYFREIGHT)); 
	    moneyProduct.setText("￥"+orderJO.getDouble(Order.MONEYPRODUCT)); 
	    shopName.setText(orderJO.getString(Order.SUPPLIERNAME)); 
	    serviceTelnum.setText(orderJO.getString(Order.SERVICETELNUM));
	    customer.setText("收货电话："+orderJO.getString(Order.CUSTOMERTELNUM));
	    address.setText(orderJO.getString(Order.MACHINEADDRESS));
	    timeAA.setText("送达时间："+orderJO.getString("timeAA"));
	    productnum.setText(orderJO.getString(Order.PRODUCTNUM));
	    productVolume.setText(orderJO.getString(Order.VOLUME)+"升");
		}
	
	private void initDateAdapter(){
		String timeAA=orderJO.getString("timeAA");
		int timeAAH= Integer.parseInt(timeAA.substring(0, 2));
		int timeAAM= Integer.parseInt(timeAA.substring(2, 4));
		Calendar ca= Calendar.getInstance();
	    islate=ca.get(Calendar.HOUR_OF_DAY)*60+ ca.get(Calendar.MINUTE)>timeAAH*60+timeAAM;
	    dates.add(ca.getTime());
	    dates.add(CommonFunction.addDay(ca.getTime(),1));
	    dates.add(CommonFunction.addDay(ca.getTime(),2));
	    dates.add(CommonFunction.addDay(ca.getTime(),3));
	    dates.add(CommonFunction.addDay(ca.getTime(),4));
	    String spcontents[]= new String[5];
	    for(int i=0;i<5;i++){
	    	int month=dates.get(i).getMonth()+1;
	   spcontents[i]=month+"月"+dates.get(i).getDate()+"日"+"  星期"+dates.get(i).getDay();
	    }
	    ArrayAdapter dateAdapter = new ArrayAdapter( this , android.R.layout. simple_spinner_item , spcontents );
	    dateAdapter.setDropDownViewResource(android.R.layout. simple_spinner_dropdown_item );
	    sp_date.setAdapter(dateAdapter);
	    sp_date.setPrompt("请选择送达日期");
	    sp_date.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
	         if(islate&&position==0){
	        	CommonFunction.alert(PlaceOrderAct.this, "选择无效", "已过今日最迟下单时间"); 
	         }else{
	        	 SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMdd",Locale.CHINA);
	        	 String dateAA=dateFormat1.format(dates.get(position));
	        	 orderJO.put(Order.DATEAA,dateAA);	        	
	        	 String dateTimeAA=dateAA+orderJO.getString("timeAA")+"00";
	        	 orderJO.put(Order.DATETIMEAA, dateTimeAA);
	        	 int timeFlag= orderJO.getInt(Order.TIMEFLAG);
	        	 if(timeFlag==1){
	        		 isDateSelected=true;
	        		orderJO.put(Order.DATETIMEAE,dateAA+Constant.machineJO.getString(Machine.TIMEAEM)+"00"); 
	        		orderJO.put(Order.DATETIMETL,dateAA+Constant.machineJO.getString(Machine.TIMETLM)+"00"); 
	        		orderJO.put(Order.DATETIMERL,dateAA+Constant.machineJO.getString(Machine.TIMERLM)+"00");	        		        		
	        	 }else if(timeFlag==2){
	        		 isDateSelected=true;
		        		orderJO.put(Order.DATETIMEAE,dateAA+Constant.machineJO.getString(Machine.TIMEAEN)+"00"); 
		        		orderJO.put(Order.DATETIMETL,dateAA+Constant.machineJO.getString(Machine.TIMETLN)+"00"); 
		        		orderJO.put(Order.DATETIMERL,dateAA+Constant.machineJO.getString(Machine.TIMERLN)+"00");	 
	        	 }else if(timeFlag==3){
	        		 isDateSelected=true;
		        		orderJO.put(Order.DATETIMEAE,dateAA+Constant.machineJO.getString(Machine.TIMEAEE)+"00"); 
		        		orderJO.put(Order.DATETIMETL,dateAA+Constant.machineJO.getString(Machine.TIMETLE)+"00"); 
		        		orderJO.put(Order.DATETIMERL,dateAA+Constant.machineJO.getString(Machine.TIMERLE)+"00");	 
	        	 }else{
	        		 CommonFunction.alert(PlaceOrderAct.this, "选择无效", "timeFlag有误，timeFlag="+timeFlag);  
	        	 }
	         }
	        }
	       @Override
	       public void onNothingSelected(AdapterView<?> arg0) {
	        // TODO Auto-generated method stub
	        }	
	        });
	
	}
	
	 private void initListenr(){
		 myClickListener= new View.OnClickListener() {		
			@Override
			public void onClick(View v) {
		      if(v==back){
		    	  new Thread () { 
						public void run () { 
						try { 									
						Instrumentation inst= new Instrumentation(); 
						inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
						} catch(Exception e) { 
						e.printStackTrace(); 
						         } 
						  } 
						}.start(); 
		      }	
		      if(v==confirm){
		    	  if(!isDateSelected){
		    		  CommonFunction.alert(PlaceOrderAct.this, "温馨提示", "请选择送达日期");  
		    		  return;
		    	  }
		    	  String[] params= new String[3];
		            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
	                params[1]="createOrder"; //PostCod
	                orderJO.put(Order.NOTE, note.getText().toString());
	                JSONObject currentOrderJO= JSONObject.fromObject(orderJO);
	                currentOrderJO.remove("timeAA");
	             /*   for(int i=0;i<currentOrderJO.getJSONArray("products").size();i++){
	                	currentOrderJO.getJSONArray("products").getJSONObject(i).remove(Product.DIR);
	                } */               
	                JSONObject json= new JSONObject();
	                json.put("order", currentOrderJO);
	                json.put("customer", Constant.customerJO);
	                params[2]=json.toString();
	                new HttpPostTaskforPlaceOrder().execute(params);
	                confirm.setVisibility(View.GONE);
	                prgs.setVisibility(View.VISIBLE);
		    	 System.out.println("confirm place order");
		    	 System.out.println(currentOrderJO.toString());
		      }
			}
		};
	 }	

class ProductListAdapter extends BaseAdapter {
	   
	
    private LayoutInflater layoutInflater;  
    private Context context;  
    private int parentPosition;
        public ProductListAdapter(Context context) {
			
		this.context = context;
	    this.layoutInflater=LayoutInflater.from(context); 
	  
	}


    final class Zujian{  
         public TextView product,branch,price,num,volume; 
       
         public  ImageView img;
      
        }  
          @Override
       public int getCount() {
	// TODO Auto-generated method stub
	    return productsJA.size();  
        	 
       }

      @Override
       public Object getItem(int position) {
	// TODO Auto-generated method stub
	       return productsJA.getJSONObject(position);  
    	 
          }

    @Override
     public long getItemId(int position) {
	// TODO Auto-generated method stub
	       return position; 
       }

               @Override
    public View getView(int position, View  convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	final int childID = position;   
	 Zujian zj=null;  
        if(convertView==null){  
            zj=new Zujian();  
            //获得组件，实例化组件  
            convertView=layoutInflater.inflate(R.layout.list_child_act_placeorder, null);  
            zj.img=(ImageView) convertView.findViewById(R.id.img_product_listchild_actplaceorder);
            
            zj.num=(TextView) convertView.findViewById(R.id.tv_branchnum_listchild_placeorderact);
            zj.branch=(TextView) convertView.findViewById(R.id.tv_branchname_listchild_placeorderact);
            zj.product=(TextView) convertView.findViewById(R.id.tv_productname_listchild_placeorderact);
            zj.price=(TextView) convertView.findViewById(R.id.tv_branchprice_listchild_placeorderact);
            zj.volume=(TextView) convertView.findViewById(R.id.tv_branchvolume_listchild_placeorderact);
            convertView.setTag(zj);  
            System.out.println("position----"+position+"------inflated");
        }else{   System.out.println("position----"+position+"-------not inflated");
            zj=(Zujian)convertView.getTag();  
        }  		        						  
        //绑定数据  
      JSONObject record=productsJA.getJSONObject(position);
        zj.num.setText(record.getInt(OrderProduct.BRANCHNUM)+"个");
        zj.price.setText(record.getDouble(OrderProduct.BRANCHPRICE)+"元");
        zj.volume.setText(record.getInt(OrderProduct.BRANCHVOLUME)+"升");
        zj.branch.setText(record.getString(OrderProduct.BRANCHNAME));
        zj.product.setText(record.getString(OrderProduct.PRODUCTNAME)); 
        
        imageLoader.showImageAsyn(zj.img, record.getString(OrderProduct.DIR), R.drawable.p3);       
        return convertView;
       } 
         }// end Adapter

private  class HttpPostTaskforPlaceOrder extends android.os.AsyncTask<String,String,Map<String,Object>>{

	

	@Override
	protected Map<String,Object> doInBackground(String... params) {
		// TODO Auto-generated method stub
		 Map<String,Object> map = new HashMap<String ,Object>();		
	  map =	UniversalHttpPost.doPost(params);	             
		return map;
	}
	
	@Override
	protected void onPostExecute(Map<String,Object> map) {
	
		 prgs.setVisibility(View.GONE);	
		 confirm.setVisibility(View.VISIBLE);
		 System.out.println("-----------onPostExecute()--------------");
		 String PostResult=(String) map.get("PostResult");		 
		 boolean networkstate=(Boolean) map.get("PostState");
		 if(!networkstate){
			 CommonFunction.alert(PlaceOrderAct.this, "下单失败", "无法连接网络");return;
	      
		}
		//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			Boolean success=false;
			String errorInfo="";
			JSONObject json = null;
			
			try{
		     json= JSONObject.fromObject(PostResult);
			 success=json.getBoolean("success");
			 errorInfo=json.getString("errorInfo");	
			}catch(JSONException e){
				 CommonFunction.alert(PlaceOrderAct.this, "下单失败", "数据解析错误");return;
			}
									   												      		       
	       if(!success){   CommonFunction.alert(PlaceOrderAct.this, "下单失败", errorInfo);return;   }
	    	  	
	  		 JSONObject carJO= new JSONObject();
	  		 carJO.put(Car.MACHINE, orderJO.getInt(Order.MACHINEID));
	  		 carJO.put(Car.SUPPLIER, orderJO.getString(Order.SUPPLIERTELNUM));
	  		 carJO.put(Car.TIMEFLAG, orderJO.getInt(Order.TIMEFLAG));
	  		 CarDao carDao= new CarDao(PlaceOrderAct.this);
	  		 for(int i=0;i<orderJO.getJSONArray("products").size();i++){  
	  			 carJO.put(Car.PRODUCT, orderJO.getJSONArray("products").getJSONObject(i).getInt(OrderProduct.PRODUCTID));
	  			 carJO.put(Car.BRANCH, orderJO.getJSONArray("products").getJSONObject(i).getInt(OrderProduct.BRANCHID));
	  			 System.out.println("delete carJO="+carJO.toString()+"RESULT=");
	  			carDao.deleteOneRecord(carJO);
	  		 }
			Intent intent = new Intent(PlaceOrderAct.this, ChoosePayAct.class);
			              intent.putExtra("order", json.getJSONObject("order").toString());
			startActivity(intent);
	  		 PlaceOrderAct.this.finish();
		
	} //onPostExecute
} //AsyncTask
	
	
}
